<template>
  <div class="food-manage">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.foodName"
            placeholder="搜索食材名称"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="searchForm.expireDate"
            type="date"
            placeholder="选择保质期"
            clearable
            @change="handleSearch"
          />
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增食材
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 食材列表 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column type="index" width="60" label="序号" />
      
      <el-table-column prop="foodName" label="食材名称" min-width="120">
        <template #default="{ row }">
          <el-tag effect="plain">{{ row.foodName }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="quantity" label="数量" width="100">
        <template #default="{ row }">
          <span>{{ row.quantity }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="expireDate" label="保质期" width="120" sortable>
        <template #default="{ row }">
          <el-tag
            :type="getExpireTagType(row.expireDate)"
            effect="light"
          >
            {{ formatDate(row.expireDate) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            link
            @click="handleEdit(row)"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            link
            @click="handleDelete(row.id)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="食材名称" prop="foodName">
          <el-input
            v-model="formData.foodName"
            placeholder="请输入食材名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="数量" prop="quantity">
          <el-input-number
            v-model="formData.quantity"
            :min="1"
            :max="9999"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item label="保质期" prop="expireDate">
          <el-date-picker
            v-model="formData.expireDate"
            type="date"
            placeholder="选择保质期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Refresh,
  Edit,
  Delete
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  foodName: '',
  expireDate: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: null,
  foodName: '',
  quantity: 1,
  expireDate: ''
})

// 表单验证规则
const formRules = {
  foodName: [
    { required: true, message: '请输入食材名称', trigger: 'blur' },
    { min: 1, max: 100, message: '食材名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入食材数量', trigger: 'blur' }
  ],
  expireDate: [
    { required: true, message: '请选择保质期', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return formData.id ? '编辑食材' : '新增食材'
})

// 生命周期
onMounted(() => {
  loadTableData()
})

// 方法定义
// 2. 修改数据加载逻辑：适配后端分页结果格式
const loadTableData = async () => {
  loading.value = true;
  try {
    const res = await mockApiCall(); // res 是后端返回的 Result 对象
    tableData.value = res.data.records; // 表格数据 = 分页结果中的 records 数组
    pagination.total = res.data.total;  // 总条数 = 分页结果中的 total
  } catch (error) {
    ElMessage.error('加载数据失败');
    console.error('加载数据失败:', error);
  } finally {
    loading.value = false;
  }
}


// 模拟API调用
const mockApiCall = async () => {
  try {
    // 拼接分页参数（current=当前页，size=每页条数）和搜索条件
    const params = new URLSearchParams({
      current: pagination.currentPage, // 对应后端 current 参数
      size: pagination.pageSize,       // 对应后端 size 参数
      foodName: searchForm.foodName || '', // 搜索条件：食材名
      expireDate: searchForm.expireDate || '' // 搜索条件：保质期
    });
    // 拼接参数到请求URL
    const response = await fetch(`http://localhost:8080/FoodAll?${params}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    });
    if (!response.ok) throw new Error('Failed to fetch data');
    const data = await response.json();
    return data; // 后端返回格式：{ code: 200, data: { records: [...], total: 100 } }
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

// 刷新
const handleRefresh = () => {
  loadTableData()
  ElMessage.success('刷新成功')
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  resetForm()
  Object.assign(formData, {
    id: row.id,
    foodName: row.foodName,
    quantity: row.quantity,
    expireDate: row.expireDate
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这个食材吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 模拟删除API调用
      await mockDeleteApi(id)
      ElMessage.success('删除成功')
      loadTableData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 模拟删除API
const mockDeleteApi = async (id) => {
  try {
    const response = await fetch(`http://localhost:8080/DeleteFood/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      throw new Error('Failed to delete data');
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error deleting data:', error);
    throw error;
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (formData.id) {
          // 编辑操作
          await mockUpdateApi(formData)
          ElMessage.success('更新成功')
        } else {
          // 新增操作
          await mockCreateApi(formData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        loadTableData()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 模拟新增API
const mockCreateApi = async (data) => {
  try {
    const response = await fetch('http://localhost:8080/AddFood', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      throw new Error('Failed to create data');
    }
    const result = await response.json();
    return result;
  } catch (error) {
    console.error('Error creating data:', error);
    throw error;
  }
}

// 模拟更新API
const mockUpdateApi = async (data) => {
  try {
    const response = await fetch('http://localhost:8080/EditFood', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      throw new Error('Failed to update data');
    }
    const result = await response.json();
    return result;
  } catch (error) {
    console.error('Error updating data:', error);
    throw error;
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    foodName: '',
    quantity: 1,
    expireDate: ''
  })
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadTableData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dateString
}

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  return dateTimeString
}

// 获取保质期标签类型
const getExpireTagType = (expireDate) => {
  if (!expireDate) return ''
  
  const today = new Date()
  const expire = new Date(expireDate)
  const diffTime = expire.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays < 0) return 'danger' // 已过期
  if (diffDays <= 3) return 'warning' // 3天内过期
  return 'success' // 正常
}
</script>

<style scoped>
.food-manage {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-right {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-table) {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>